package com.seckill.seckilldemo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {
    /**
     * 创建并配置Cookie
     */
    public static Cookie createCookie(String name, String value, int time, String path){
        Cookie cookie = new Cookie(name, value);
        //Cookie的一些其他设置，可以设置最大有效期，可以设置有效范围(在哪里能够获取到该Cookie信息)
        //设置有效期
        cookie.setMaxAge(time);
        //设置有效范围
        cookie.setPath(path);//只能在CookieDemo02这个Servlet中获取该Cookie的信息
        return cookie;
    }
    public static String getCookieValue(HttpServletRequest request, String cookieName){
        return getCookieValue(request,cookieName,false);
    }
    public static String getCookieValue(HttpServletRequest request, String cookieName,boolean isDecoder){
        Cookie[] cookies = request.getCookies();
        String retValue = null;
        try{
            for(int i = 0 ; i < cookies.length ; i ++){
                if(cookies[i].getName().equals(cookieName)){
                    if(isDecoder){
                        retValue = URLDecoder.decode(cookies[i].getValue(),"UTF-8");
                    }else {
                        retValue = cookies[i].getValue();
                    }
                }
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return retValue;
    }
    public static String getCookieValue(HttpServletRequest request, String cookieName,String encodeString){
        Cookie[] cookies = request.getCookies();
        String retValue = null;
        try{
            for(int i = 0 ; i < cookies.length ; i ++){
                if(cookies[i].getName().equals(cookieName)){
                    retValue = URLDecoder.decode(cookies[i].getValue(),encodeString);
                    break;
                }
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return retValue;
    }
    //设置cookie的值，不设置关闭时间即默认浏览器关闭即失效，也不编码
    public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                 String cookieValue){
        setCookie(request,response,cookieName,cookieValue,-1);
    }
    //设置cookie的值，在指定时间生效，但是不编码
    public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxAge){
        setCookie(request,response,cookieName,cookieValue,cookieMaxAge,false);
    }
    //设定cookie的值，不设置生效时间，但编码
    public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                 String cookieValue,boolean isEncode){
        setCookie(request,response,cookieName,cookieValue,-1,isEncode);
    }
    //设置cookie的值，编码参数，指定时间
    public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxAge,boolean isEncode){
        doSetCookie(request,response,cookieName,cookieValue,cookieMaxAge,isEncode);
    }
    //设置cookie的值，在指定时间生效，指定编码参数
    public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxAge,String encodeString){
        doSetCookie(request,response,cookieName,cookieValue,cookieMaxAge,encodeString);
    }

    //删除带cookie的域名
    public static void deleteCookie(HttpServletRequest request,HttpServletResponse response,String cookieName){
        doSetCookie(request,response,cookieName,"",-1,false);
    }


    public static final void doSetCookie(HttpServletRequest request,HttpServletResponse response,
                                         String cookieName,String cookieValue,int cookieMaxAge,
                                         boolean isEncode) {
        try {
            if(cookieValue == null){
                cookieValue = "";
            }else if(isEncode){
                cookieValue = URLEncoder.encode(cookieValue,"UTF-8");
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if(cookieMaxAge > 0){
                cookie.setMaxAge(cookieMaxAge);
            }
            if(null != request){//设置域名的cookie
                String domainName = getDomainName(request);
                //System.out.println(domainName);
                if(!"localhost".equals(domainName)){
                    cookie.setDomain(domainName);
                }
            }
            //该句可以让webapp下所有文件共享cookie
            cookie.setPath("/");
            response.addCookie(cookie);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    public static final void doSetCookie(HttpServletRequest request,HttpServletResponse response,
                                         String cookieName,String cookieValue,int cookieMaxAge,
                                         String encodeString){
        try {
            if(cookieValue == null){
                cookieValue = "";
            }else{
                cookieValue = URLEncoder.encode(cookieValue,encodeString);
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if(cookieMaxAge > 0){
                cookie.setMaxAge(cookieMaxAge);
            }
            if(null != request){//设置域名的cookie
                String domainName = getDomainName(request);
                //System.out.println(domainName);
                if(!"localhost".equals(domainName)){
                    cookie.setDomain(domainName);
                }
            }
            //该句可以让webapp下所有文件共享cookie
            cookie.setPath("/");
            response.addCookie(cookie);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }

    //得到cookie的域名
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
        String serverName = request.getServerName().toString();
        //System.out.println(serverName);
        if(serverName == null || serverName.equals("")){
            domainName = "";
        }else{
            //将Url地下转为小写
            serverName = serverName.toLowerCase();
            if(serverName.startsWith("http://")){
                serverName = serverName.substring(7);
            }
            int end = serverName.length();
            if(serverName.contains("/")){
                //得到第一个"/"出现的位置
                end = serverName.indexOf("/");
            }
            //截取
            serverName = serverName.substring(0,end);
            //根据.进行分割
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if(len > 3){
                //www.xxx.com.cn
                domainName = domains[len - 4] + "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            }else if(len > 1){
                //xxx.com || xxx.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            }else {
                domainName = serverName;
            }
        }
        if(domainName != null && domainName.indexOf(":") > 0){
            String[] array = domainName.split("\\:");
            domainName = array[0];
        }
        return domainName;
    }

}

